package org.citra.citra_emu.features.settings.model;

import android.text.TextUtils;

import com.aiwu.ConfigManager;
import com.aiwu.bean.ConfigBean;

import org.citra.citra_emu.CitraApplication;
import org.citra.citra_emu.NativeLibrary;
import org.citra.citra_emu.R;
import org.citra.citra_emu.features.settings.ui.SettingsActivityView;
import org.citra.citra_emu.features.settings.utils.SettingsFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Settings {
    public static final String SECTION_PREMIUM = "Premium";
    public static final String SECTION_CORE = "Core";
    public static final String SECTION_SYSTEM = "System";
    public static final String SECTION_CAMERA = "Camera";
    public static final String SECTION_CONTROLS = "Controls";
    public static final String SECTION_RENDERER = "Renderer";
    public static final String SECTION_LAYOUT = "Layout";
    public static final String SECTION_AUDIO = "Audio";
    public static final String SECTION_DEBUG = "Debug";

    private String gameId;

    private static final Map<String, List<String>> configFileSectionsMap = new HashMap<>();

    static {
        configFileSectionsMap.put(SettingsFile.FILE_NAME_CONFIG, Arrays.asList(SECTION_PREMIUM, SECTION_CORE, SECTION_SYSTEM, SECTION_CAMERA, SECTION_CONTROLS, SECTION_RENDERER, SECTION_AUDIO, SECTION_DEBUG, SECTION_LAYOUT));
    }

    /**
     * A HashMap<String, SettingSection> that constructs a new SettingSection instead of returning null
     * when getting a key not already in the map
     */
    public static final class SettingsSectionMap extends HashMap<String, SettingSection> {
        @Override
        public SettingSection get(Object key) {
            if (!(key instanceof String)) {
                return null;
            }

            String stringKey = (String) key;

            if (!super.containsKey(stringKey)) {
                SettingSection section = new SettingSection(stringKey);
                super.put(stringKey, section);
                return section;
            }
            return super.get(key);
        }
    }

    private HashMap<String, SettingSection> sections = new Settings.SettingsSectionMap();

    public SettingSection getSection(String sectionName) {
        return sections.get(sectionName);
    }

    public boolean isEmpty() {
        return sections.isEmpty();
    }

    public HashMap<String, SettingSection> getSections() {
        return sections;
    }

    public void loadSettings(SettingsActivityView view) {
        sections = new Settings.SettingsSectionMap();
        loadCitraSettings(view);

        if (!TextUtils.isEmpty(gameId)) {
            loadCustomGameSettings(gameId, view);
        }
        loadMySettings();
    }

    private void loadCitraSettings(SettingsActivityView view) {
        for (Map.Entry<String, List<String>> entry : configFileSectionsMap.entrySet()) {
            String fileName = entry.getKey();
            sections.putAll(SettingsFile.readFile(fileName, view));
        }
    }

    private void loadCustomGameSettings(String gameId, SettingsActivityView view) {
        // custom game settings
        mergeSections(SettingsFile.readCustomGameSettings(gameId, view));
    }

    private void mergeSections(HashMap<String, SettingSection> updatedSections) {
        for (Map.Entry<String, SettingSection> entry : updatedSections.entrySet()) {
            if (sections.containsKey(entry.getKey())) {
                SettingSection originalSection = sections.get(entry.getKey());
                SettingSection updatedSection = entry.getValue();
                originalSection.mergeSection(updatedSection);
            } else {
                sections.put(entry.getKey(), entry.getValue());
            }
        }
    }

    public void loadSettings(String gameId, SettingsActivityView view) {
        this.gameId = gameId;
        loadSettings(view);
    }

    public void saveSettings(SettingsActivityView view) {
        if (TextUtils.isEmpty(gameId)) {
            if (view != null)
                view.showToastMessage(CitraApplication.getAppContext().getString(R.string.ini_saved), false);

            for (Map.Entry<String, List<String>> entry : configFileSectionsMap.entrySet()) {
                String fileName = entry.getKey();
                List<String> sectionNames = entry.getValue();
                TreeMap<String, SettingSection> iniSections = new TreeMap<>();
                for (String section : sectionNames) {
                    iniSections.put(section, sections.get(section));
                }

                SettingsFile.saveFile(fileName, iniSections, view);
            }
            //region 修改
            ConfigManager.getInstance().resetTempConfigIfNecessary();
            //endregion
        } else {
            // custom game settings
            if (view != null)
                view.showToastMessage(CitraApplication.getAppContext().getString(R.string.gameid_saved, gameId), false);

            SettingsFile.saveCustomGameSettings(gameId, sections);
        }

    }

    //region修改
    private void loadMySettings() {
        int[] array = NativeLibrary.GetMyConfigValue();
        if (array.length != 5) {
            return;
        }
        int useAsynchronousGpuEmulation = array[0];
        if (useAsynchronousGpuEmulation != ConfigBean.DEFAULT_VALUE) {
            SettingSection rendererSection = getSection(Settings.SECTION_RENDERER);
            Setting gSetting = rendererSection.getSetting(SettingsFile.KEY_USE_ASYNCHRONOUS_GPU_EMULATION);
            if (gSetting != null) {
                ConfigManager.getInstance().setOriginalGpuValue(gSetting.getValueAsString());
                ((IntSetting) gSetting).setValue(useAsynchronousGpuEmulation);
            } else {
                rendererSection.putSetting(new IntSetting(SettingsFile.KEY_USE_ASYNCHRONOUS_GPU_EMULATION, Settings.SECTION_RENDERER, useAsynchronousGpuEmulation));
            }
        }

        int shadersAccurateMul = array[1];
        if (shadersAccurateMul != ConfigBean.DEFAULT_VALUE) {
            SettingSection rendererSection = getSection(Settings.SECTION_RENDERER);
            Setting aSetting = rendererSection.getSetting(SettingsFile.KEY_SHADERS_ACCURATE_MUL);
            if (aSetting != null) {
                ConfigManager.getInstance().setOriginalAccurateMulValue(aSetting.getValueAsString());
                ((IntSetting) aSetting).setValue(shadersAccurateMul);
            } else {
                rendererSection.putSetting(new IntSetting(SettingsFile.KEY_SHADERS_ACCURATE_MUL, Settings.SECTION_RENDERER, shadersAccurateMul));
            }
        }
        int regionValue = array[2];
        if (regionValue != ConfigBean.DEFAULT_VALUE) {
            SettingSection systemSection = getSection(Settings.SECTION_SYSTEM);
            Setting region = systemSection.getSetting(SettingsFile.KEY_REGION_VALUE);
            if (region != null) {
                ConfigManager.getInstance().setOriginalRegion(region.getValueAsString());
                ((IntSetting) region).setValue(regionValue);
            } else {
                systemSection.putSetting(new IntSetting(SettingsFile.KEY_REGION_VALUE, Settings.SECTION_SYSTEM, regionValue));
            }
        }
        int language = array[3];
        if (language != ConfigBean.DEFAULT_VALUE) {
            SettingSection systemSection = getSection(Settings.SECTION_SYSTEM);
            Setting lSetting = systemSection.getSetting(SettingsFile.KEY_LANGUAGE);
            if (lSetting != null) {
                ConfigManager.getInstance().setOriginalLanguage(lSetting.getValueAsString());
                ((IntSetting) lSetting).setValue(language);
            } else {
                systemSection.putSetting(new IntSetting(SettingsFile.KEY_LANGUAGE, Settings.SECTION_SYSTEM, language));
            }
        }
        int isNew3DS = array[4];
        if (isNew3DS != ConfigBean.DEFAULT_VALUE) {
            SettingSection systemSection = getSection(Settings.SECTION_SYSTEM);
            Setting lSetting = systemSection.getSetting(SettingsFile.KEY_IS_NEW_3DS);
            if (lSetting != null) {
                ConfigManager.getInstance().setOriginalIsNew3DS(lSetting.getValueAsString());
                ((IntSetting) lSetting).setValue(language);
            } else {
                systemSection.putSetting(new IntSetting(SettingsFile.KEY_IS_NEW_3DS, Settings.SECTION_SYSTEM, language));
            }
        }
    }
    //endregion
}